﻿;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.HandoverBill4JCK", [])
        .controller("HandoverBill4JCKCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "EventBus", "Upload", "ybConfig", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, EventBus, Upload, ybConfig, UserContextService) {
            $scope.activeFlag = [true, false, false, false];
            $scope.datePickerFlag = [false, false, false, false, false, false];
            $scope.subTabFlag = [true, false];
            $scope.materials = [];
            $scope.markInfo = {
                allChecked: false
            };

            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderMarkInfo = {
                allChecked: false
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            $scope.orderCondition = {
                status: '1'
            };
            $scope.dataList = [];
            $scope.orderDataList = [];
            $scope.billDetailDataList = [];
            $scope.selectedList = [];
            $scope.detailInfo = {
                sex: 1,
                locked: 0,
                deliveryReceiptVO: {},
                billList: [],
                basicAttachmentList: []
            };
            $scope.abnormalObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.innerOrderList = [];
            $scope.innerOrder = {
                item: null
            };
            $scope.dataSelected = {
                role: {},
                department: {}
            };
            $scope.inTypeList = [];
            $scope.deliveryStatues = [];
            $scope.tabFlag = {};
            $scope.stepList = {
                curStep: 0,
                list: [{
                    name: '选择发货通知单'
                }, {
                    name: '生成发运交接单'
                }]
            };
            $scope.showDatepicker = false;
            $scope.showDatepicker1 = false;

            $scope.showCommitmentTime = false;
            $scope.warehouseList = [{
                code: null,
                name: "请选择"
            }];
            $scope.billTypeList = [{
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                },
                {
                    code: "XGQD",
                    name: "区域调拨单"
                },
                {
                    code: "XGFC",
                    name: "其它出库单"
                },
                // wangcan:单据类型增加销售赠送出库
                {
                    code: "XSCK",
                    name: "销售赠送出库"
                }
            ];
            $scope.threeDayBillTypeList = [{
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                }
            ];
            var billType = "";
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.tableConfig = {
                scrollWidth: 1300,
                fixedWidth: 670,
                tableCol: [
                    {
                        type: "",
                        name: "进出口单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail"
                    },
                    {
                        type: "",
                        name: "采购合同单号",
                        dataField: "purchaseContractNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "国家和地区",
                        dataField: "country",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "业务部门",
                        dataField: "deptName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "业务员",
                        dataField: "salesName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "运输方式",
                        dataField: "shippingMethod",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "运输费用",
                        dataField: "carrierAmountShow",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "辅料费用",
                        dataField: "accessoriesFeeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "deliveryStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "同步NS系统状态",
                        dataField: "syncNsStatusShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "确认发运时间",
                        dataField: "commitTimeShow",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 630,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };

            //新增时左侧列表配置项
            $scope.addLeftTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "业务单号",
                        dataField: "deliveryNo",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 100,
                        isShow: false,
                        isFixed: false,
                        toSort: true,
                        sortType: ''
                    },
                    {
                        type: "",
                        name: "国家和地区",
                        dataField: "country",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建帐号",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateStr",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务网点",
                        dataField: "serviceSite",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                ]
            };


            $scope.abnormalInNewTbConf = {
                scrollWidth: 950,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "分类",
                        width: 150,
                        dataField: "materialsType",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 120,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "数量",
                        width: 150,
                        dataField: "outQty",
                        input: false,
                        inputType: "txt"
                    },
                    {
                        name: "已建入库数量",
                        width: 150,
                        dataField: "sendQty",
                        input: false,
                        inputType: "txt"
                    },
                    {
                        name: "本次入库数量",
                        width: 150,
                        dataField: "amount",
                        input: false,
                        inputType: "txt"
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "note",
                        input: true,
                        inputType: "note"
                    }
                ]
            };

            var btnPermissionCode = {
                handoverBillJCKAdd: window.ActionCode.handoverBillJCKAdd,
                handoverBillJCKEdit: window.ActionCode.handoverBillJCKEdit,
                handoverBillJCKPrint: window.ActionCode.handoverBillJCKPrint,
                handoverBillJCKExport: window.ActionCode.handoverBillJCKExport,
                handoverBillJCKAbnormalIn: window.ActionCode.handoverBillJCKAbnormalIn,
                handoverBillJCKRemove: window.ActionCode.handoverBillJCKRemove,
                handoverBillJCKSend: window.ActionCode.handoverBillJCKSend,
                handoverBillJCKThreeDayPlan: window.ActionCode.handoverBillJCKThreeDayPlan,
                handoverBillJCKReceive: window.ActionCode.handoverBillJCKReceive,
                handoverBillJCKTJSC: window.ActionCode.handoverBillJCKTJSC,
                handoverSaveDetailDataJck: window.ActionCode.handoverSaveDetailDataJck,
                handoverBillJCKSyncPackInfo: window.ActionCode.handoverBillJCKSyncPackInfo,
                handoverBillJCKEncasementJck: window.ActionCode.handoverBillJCKEncasementJck,
                handoverBillJCKSyncDelivery4NSJck: window.ActionCode.handoverBillJCKSyncDelivery4NSJck,
                handoverBillJCKBachExport: window.ActionCode.handoverBillJCKBachExport,
            };

            $scope.btnPermission = {
                handoverBillJCKAdd: true,
                handoverBillJCKEdit: true,
                handoverBillJCKPrint: true,
                handoverBillJCKExport: true,
                handoverBillJCKAbnormalIn: true,
                handoverBillJCKRemove: true,
                handoverBillJCKSend: true,
                handoverBillJCKThreeDayPlan: true,
                handoverBillJCKReceive: true,
                handoverBillJCKTJSC: true,
                handoverSaveDetailDataJck: true,
                handoverBillJCKEncasementJck: true,
                handoverBillJCKSyncDelivery4NSJck: true,
                handoverBillJCKBachExport: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    billFixedWidth: {
                        left: $scope.addLeftTableConfig.fixedWidth + "px"
                    }
                };
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/export4Jck"),
                sectionParam: {
                    billIds: []
                },
                allUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/exportAll4Jck"),
                allNewUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/exportAllNew"),
                exportUrl: ybHttp.RequestUrl("device", "/boxupDetail/remove"),
                exportUrl4Jck: ybHttp.RequestUrl("device", "/boxupDetail/export4Jck"),
                barchExportUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/export4JckByBillId"),
                exportBoxUp: ybHttp.RequestUrl("device", "/deliveryReceipt/exportBoxUp4Batch"),
            };

            $scope.exportBillDetailParam = {
                url: ybHttp.RequestUrl("device", "/deliveryReceipt/exportBillDetail"),
                param: {
                    billType: "",
                    deliveryBillId: ""
                }
            }

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.sortObj = {};

                $scope.tabFlag = {};
                $scope.detailInfo = {
                    sex: 1,
                    locked: 0,
                    deliveryReceiptVO: {},
                    billList: [],
                    basicAttachmentList: []
                };
                $scope.abnormalObj = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.innerOrder = {
                    item: null
                };
                $scope.selectedList = [];
                $scope.stepList.curStep = 0;
                $scope.dataSelected = {
                    role: {},
                    department: {}
                };
                billType = "";
                $scope.billDetailDataList = [];
            }

            function getDataList(curPage) {
                $scope.exportParam.sectionParam.billIds = [];
                var service = "device";
                var reqUrl = "/deliveryReceipt/list4JckOverseas";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.outStatusShow = $filter("ProgressStatus")(item.outStatus, 'outDepot');
                        item.syncNsStatusShow = $filter("ProgressStatus")(item.syncNsStatus, 'syncNsStatus');
                        item.deliveryStatusShow = $filter("ProgressStatus")(item.deliveryStatus, 'deliveryStatus');
                        item.isAbnormal = item.isAbnormal === 1 ? "是" : "否";
                        item.accessoriesFeeShow = (!!item.accessoriesFee || item.accessoriesFee == 0) ? $filter("decimalPlaces")(item.accessoriesFee, 2) : undefined;
                        item.carrierAmountShow = (!!item.carrierAmount || item.carrierAmount == 0) ? $filter("decimalPlaces")(item.carrierAmount, 2) : undefined;
                        item.commitTimeShow = $filter("YbDate")(item.commitTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function changeField(headerInfo) {
                $scope.detailInfo.deliveryReceiptVO = angular.copy(headerInfo);
                $scope.detailInfo.deliveryReceiptVO.dealerOrgId = headerInfo.purchaseOrgId;
                $scope.detailInfo.deliveryReceiptVO.dealerOrgName = headerInfo.purchaseOrgName;
                $scope.detailInfo.deliveryReceiptVO.orgName = headerInfo.supplierOrgName;
                $scope.detailInfo.deliveryReceiptVO.createOrgName = headerInfo.createCompanyName;
                $scope.detailInfo.deliveryReceiptVO.shippingMethod = headerInfo.deliveryTypeName;
                $scope.detailInfo.deliveryReceiptVO.settlementId = headerInfo.settleTypeId;
                $scope.detailInfo.deliveryReceiptVO.settlementDesc = headerInfo.settleTypeName;
                $scope.detailInfo.deliveryReceiptVO.receiverName = headerInfo.receiverName;
                $scope.detailInfo.deliveryReceiptVO.receiverTel = headerInfo.receiverPhone;
                $scope.detailInfo.deliveryReceiptVO.receiverFax = headerInfo.receiverFax;
                $scope.detailInfo.deliveryReceiptVO.receiverAddress = headerInfo.address;
                $scope.detailInfo.deliveryReceiptVO.addressCode = headerInfo.addressCode;
                $scope.detailInfo.deliveryReceiptVO.billType = headerInfo.billType;
                $scope.detailInfo.deliveryReceiptVO.createDate = +new Date();
                $scope.detailInfo.deliveryReceiptVO.deliveryDate = '';
                $scope.detailInfo.deliveryReceiptVO.deliveryTime = $filter("YbDate")(headerInfo.deliveryDate, 'yyyy-MM-dd');
                $scope.detailInfo.deliveryReceiptVO.salesType = '0';
                $scope.detailInfo.deliveryReceiptVO.dispatcherName = headerInfo.dispatcherName;
                $scope.detailInfo.deliveryReceiptVO.carrierOrgName = !!headerInfo.carrier ? headerInfo.carrier : '';
                $scope.detailInfo.deliveryReceiptVO.carrierUserName = !!headerInfo.carrierPerson ? headerInfo.carrierPerson : '';
            }

            $scope.orderSelectAll = function () {
                angular.forEach($scope.orderDataList, function (item) {
                    if ($scope.orderMarkInfo.allChecked && !item.isChecked) {
                        item.isChecked = true;
                        $scope.selectedList.push(item);
                    }
                    if (!$scope.orderMarkInfo.allChecked && item.isChecked) {
                        item.isChecked = false;
                        for (var i = 0; i < $scope.selectedList.length; i++) {
                            if (item.deliveryNo == $scope.selectedList[i].deliveryNo) {
                                $scope.selectedList.splice(i, 1);
                                i--;
                            }
                        }
                    }
                })
            };
            $scope.orderSelectSingle = function (item) {
                if (item.isChecked) {
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].deliveryNo === item.deliveryNo) {
                            return;
                        }
                    }
                    $scope.selectedList.push(item);
                    $scope.orderMarkInfo.allChecked = true;
                    angular.forEach($scope.orderDataList, function (item) {
                        if (!item.isChecked) {
                            $scope.orderMarkInfo.allChecked = false;
                        }
                    })
                } else {
                    $scope.orderMarkInfo.allChecked = false;
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].deliveryNo == item.deliveryNo) {
                            $scope.selectedList.splice(i, 1);
                            i--;
                        }
                    }
                }
            };
            $scope.delSelected = function (index) {
                angular.forEach($scope.orderDataList, function (item) {
                    if (item.deliveryNo == $scope.selectedList[index].deliveryNo) {
                        item.isChecked = false;
                        $scope.orderMarkInfo.allChecked = false;
                    }
                });
                $scope.selectedList.splice(index, 1);
            };
            $scope.selectDealer = function () {
                var param = {
                    name: "申请单位",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.dealerOrgName = data.companyName;
                    $scope.detailInfo.deliveryReceiptVO.customerId = data.id;
                    $scope.detailInfo.deliveryReceiptVO.dealerOrgId = data.dealerOrgId;
                })
            };
            $scope.nextStep = function () {
                var tempArr = [];
                for (var i = 0, leng = $scope.selectedList.length; i < leng - 1; i++) {
                    if (trimALl($scope.selectedList[i].country) !== trimALl($scope.selectedList[i + 1].country)) {
                        ybWidget.ShowMessage('只能选择同一个国家的发运单');
                        return;
                    }

                    if (isInArray(tempArr, $scope.selectedList[i].deliveryNo)) {
                        ybWidget.ShowMessage('发运单不能重复，' + $scope.selectedList[i].deliveryNo);
                        return;
                    }
                    tempArr.push($scope.selectedList[i].deliveryNo);
                }
                $scope.detailInfo.threeDayPlan = $scope.tabFlag.isThreeDayPlan ? 1 : 0;
                $scope.detailInfo.planDate = $scope.orderCondition.planDate;
                $scope.detailInfo.billList = [];
                angular.forEach($scope.selectedList, function (item) {
                    var threeGuaServiceVO = {
                        prodType: item.prodType,
                        machineNumber: item.machineNumber,
                        crmOrder: item.crmOrder,
                        serviceName: item.serviceName,
                        serviceSite: item.serviceSite,
                    }
                    var obj = {
                        saleBillNo: item.saleNo,
                        deliveryNoteId: item.id,
                        deliveryNoteNo: item.deliveryNo,
                        purchaseBillNo: item.purchaseNo,
                        remark: item.note,
                        billType: item.billType,
                        bId: item.bId || '',
                        threeGuaServiceVO: threeGuaServiceVO,
                        status: item.status,

                    };
                    $scope.detailInfo.billList.push(obj);
                });

                $scope.markInfoForAdd = {};
                $scope.materialsForAdd = [];
                $scope.selectRowForAdd($scope.detailInfo.billList[0], 0);

                getList4MaterialInfoWeight();

                ybHttp.Get('device', '/deliveryReceipt/outBillItem', {
                    id: $scope.selectedList[i].id,
                    billType: $scope.orderCondition.billType
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    changeField(resp.value || {});
                    $scope.stepList.curStep = 1;
                })
            };

            function isInArray(arr, value) {
                for (var i = 0; i < arr.length; i++) {
                    if (value === arr[i]) {
                        return true;
                    }
                }
                return false;
            }

            function trimALl(str) {
                if (!str) {
                    return str;
                }
                return str.replace(/(^\s*)|(\s*$)/g, "");
            }

            $scope.prevStep = function () {
                $scope.stepList.curStep = 0;
            };

            $scope.sortObj = {};
            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                $scope.sortObj.sortMethod = ybWidget.ToSort(config, index);
                $scope.sortObj.sortClumn = config[index].dataField;
                getBillList(1);
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };
            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.selectForAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                getBillIds();
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.billIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.billIds.push(item.id);
                    }
                });
            }

            $scope.addData = function () {
                $scope.tabFlag = {
                    type: 0,
                    name: tabFlag[0],
                    isThreeDayPlan: false
                };
                $scope.orderCondition.billType = "XGFT";
                billType = "XGFT";
                getBillList(1);
                $scope.changeTab(1);
            };

            $scope.addThreeDayPlay = function () {
                $scope.tabFlag = {
                    type: 0,
                    name: tabFlag[0],
                    isThreeDayPlan: true
                };
                $scope.orderCondition.billType = "XGFT";
                billType = "XGFT";
                $scope.orderCondition.planDate = new Date();
                getBillList(1);
                $scope.changeTab(1);
            };

            function getBillList(curPage) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/outBillList";
                if ($scope.tabFlag.isThreeDayPlan) {
                    reqUrl = "/deliveryReceipt/threeDayPlanBillList";
                }
                var param = {};
                param.pageSize = $scope.orderPageInfo.pageSize;
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.orderPageInfo.curPage;
                param.filters = {
                    billType: $scope.orderCondition.billType,
                    warehouseCode: $scope.orderCondition.warehouseCode,
                    planDate: $scope.orderCondition.planDate,
                    keyWords: $scope.orderCondition.keWords,
                    sortClumn: $scope.sortObj.sortClumn,
                    sortMethod: $scope.sortObj.sortMethod,
                    queryType: 1
                };
                $scope.orderDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    // 处理没有list的bug
                    resp.value.list = resp.value.list || [];
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate);
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            $scope.searchBill = function (curPage) {
                getBillList(curPage);
            };

            $scope.changeBillType = function () {
                $scope.sortObj = {};

                billType = $scope.orderCondition.billType;
                var dynamicPros = ['serviceName', 'serviceSite', 'createName', 'serviceNo'];
                angular.forEach($scope.addLeftTableConfig.tableCol, function (item) {
                    if (dynamicPros.indexOf(item.dataField) !== -1) {
                        item.isShow = billType == 'XGSC'
                    }
                })
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.changeWarehouse = function () {
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.changePlanDate = function () {
                $scope.checkDate($scope.orderCondition, 'planDate');
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.delData = function (delType, userId) {
                var service = "device";
                var reqUrl = "/profile/remove";
                var param = {};
                param.userIds = [];

                if (delType === "single") {
                    param.userIds.push(userId);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            param.userIds.push($scope.dataList[i].userId);
                        }
                    }
                    if (param.userIds.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.userIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.selectLogisticsCom = function () {
                var param = {
                    name: "承运物流",
                    type: "carrier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.carrierOrgId = data.orgId;
                    $scope.detailInfo.deliveryReceiptVO.carrierOrgName = data.companyName;
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = "";
                    $scope.detailInfo.deliveryReceiptVO.commitmentTime = "";
                    $scope.detailInfo.deliveryReceiptVO.basicId = "";
                })
            };

            $scope.selectExpressCode = function () {
                var param = {
                    name: "物流商",
                    type: "logistics"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.expressCode = data.expressCode;
                    $scope.detailInfo.deliveryReceiptVO.expressName = data.expressName;
                })
            };

            $scope.selectLineCom = function () {
                if (!$scope.detailInfo.deliveryReceiptVO.carrierOrgId) {
                    ybWidget.ShowToaster('error', '请选择承运商');
                    return;
                }
                var param = {
                    name: "线路",
                    type: "line",
                    carrierOrgId: $scope.detailInfo.deliveryReceiptVO.carrierOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.commitmentTime = data.commitmentTime;
                    $scope.detailInfo.deliveryReceiptVO.basicId = data.id;
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = data.departureCity + "~" + data.destinationCity;
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/getFreight";
                    ybHttp.Get(service, reqUrl, {
                        totalWeight: $scope.totalWeight,
                        logisticsBasicId: $scope.detailInfo.deliveryReceiptVO.basicId
                    }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")(resp.value || 0, 2);
                    });
                })
            };

            $scope.selectBill = function () {
                $scope.selectBillFlag = true;
                var deliveryBillIds = [];
                angular.forEach($scope.detailInfo.billList, function (item) {
                    deliveryBillIds.push(item.deliveryNoteId);
                });
                var param = {
                    billType: billType,
                    planDate: $scope.detailInfo.planDate,
                    purchaseOrgId: $scope.detailInfo.deliveryReceiptVO.dealerOrgId,
                    deliveryBillIds: deliveryBillIds
                };
                if ($scope.detailInfo.threeDayPlan) param.threeDayPlan = true;
                ybWidget.DeliveryNoteSelector(param).then(function (data) {
                    var deliveryNoteItem = {
                        deliveryBillId: $scope.detailInfo.deliveryReceiptVO.id,
                        deliveryBillNo: $scope.detailInfo.deliveryReceiptVO.billNo,
                        deliveryNoteId: data.id,
                        deliveryNoteNo: data.deliveryNo,
                        purchaseBillId: '',
                        purchaseBillNo: data.purchaseNo,
                        remark: '',
                        saleBillId: '',
                        saleBillNo: data.saleNo,
                        bId: data.bId,

                        status: data.status
                    };
                    $scope.detailInfo.billList.push(deliveryNoteItem);

                    getList4MaterialInfoWeight();
                })
            };

            function getFreight() {
                var service = "device";
                var reqUrl = "/deliveryReceipt/getFreight";
                ybHttp.Get(service, reqUrl, {
                    totalWeight: $scope.totalWeight,
                    logisticsBasicId: $scope.detailInfo.deliveryReceiptVO.basicId
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.deliveryReceiptVO.freight = resp.value;
                });
            }

            function viewDetail(item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/item";
                var param = {};
                param.billId = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var dateFrame = "";
                    $scope.subTabFlag = [true, false];
                    $scope.changeTab(2);
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.deliveryReceiptVO.totalWeight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.totalWeight || 0, 2);
                    $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.freight || 0, 2);
                    if (resp.value.logisticsVOList.length > 0) {
                        dateFrame = $filter("YbDate")(resp.value.logisticsVOList[0].createDate);
                        resp.value.logisticsVOList[0].showDate = true;
                    }
                    for (var i = 1, len = resp.value.logisticsVOList.length; i < len; i++) {
                        resp.value.logisticsVOList[i].showDate = true;
                        if ($filter("YbDate")(resp.value.logisticsVOList[i].createDate) === dateFrame) {
                            resp.value.logisticsVOList[i].showDate = false;
                        } else {
                            dateFrame = $filter("YbDate")(resp.value.logisticsVOList[i].createDate);
                        }
                    }

                    $scope.detailInfo = resp.value;

                    EventBus.Publish("setTimeShow", $scope.detailInfo.logisticsVOList);
                });
            }

            $scope.printBill = function (item) {
                var param = {
                    billId: [item.id],
                    printType: "Handover"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.printEncasement = function (item) {
                var param = {
                    billId: [item.id],
                    printType: 'Encasement',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.printEncasementJck = function (item) {
                var param = {
                    billId: [item.id],
                    printType: 'Encasement4JCK',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.delivery = function (item) {
                $scope.detailInfo.deliveryReceiptVO.isAbnormal = !item.isAbnormal ? 0 : (item.isAbnormal === '否' ? 0 : 1);
                $scope.detailInfo.deliveryReceiptVO.remark = item.remark;
                $scope.detailInfo.deliveryReceiptVO.id = item.id;
                if (item.attachName) {
                    var fileObj = {};
                    fileObj.name = item.attachName;
                    fileObj.value = item.attachName;
                    $scope.detailInfo.basicAttachmentList.push(fileObj);
                }
                $scope.changeTab(4);
            };
            $scope.deliveryConfirm = function () {
                var service = "device";
                var reqUrl = "/deliveryReceipt/confirmReceipt";
                if ($scope.detailInfo.deliveryReceiptVO.isAbnormal) {
                    if (!$scope.detailInfo.deliveryReceiptVO.remark) {
                        ybWidget.ShowMessage("请填写备注", MESG_TYPE.Error);
                        return;
                    }
                    reqUrl = "/deliveryReceipt/refusedReceipt";
                }
                var param = {};
                param.id = $scope.detailInfo.deliveryReceiptVO.id;
                param.receiveMessage = $scope.detailInfo.deliveryReceiptVO.remark;
                param.isAbnormal = $scope.detailInfo.deliveryReceiptVO.isAbnormal;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    getDataList();
                    $scope.changeTab(0);
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };
            $scope.editBox = function (item) {
                var param = item;
                ybWidget.BoxEditMsg(param).then(function (value) {
                    var service = "device";
                    var reqUrl = "/boxup/update";
                    ybHttp.Post(service, reqUrl, value).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        item = value;
                    });
                });
            }
            $scope.editData = function (item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/item";
                var param = {};
                param.billId = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                    $scope.stepList.curStep = 1;
                    if (resp.value.planDate) {
                        resp.value.planDate = $filter("YbDate")(resp.value.planDate);
                    }
                    $scope.detailInfo = resp.value;
                    $scope.totalWeight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.totalWeight || 0, 2);
                    $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.freight || 0, 2);
                    billType = resp.value.deliveryReceiptVO.billType;
                    if (resp.value.deliveryReceiptVO.deliveryTime) {
                        $scope.detailInfo.deliveryReceiptVO.deliveryTime = new Date(resp.value.deliveryReceiptVO.deliveryTime);
                    }
                    if (resp.value.deliveryReceiptVO.deliveryDate) {
                        $scope.detailInfo.deliveryReceiptVO.deliveryDate = new Date(resp.value.deliveryReceiptVO.deliveryDate);
                    }
                    if ($scope.detailInfo.deliveryReceiptVO.basicId) {
                        getLine($scope.detailInfo.deliveryReceiptVO.basicId)
                    }
                });
            };

            function getLine(basicId) {
                var service = 'device';
                var reqUrl = '/logisticsBasic/item';
                var param = {
                    id: basicId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = resp.value.departureCity + "~" + resp.value.destinationCity;
                });

            }
            $scope.clickValue = false;
            $scope.saveDataflag = 0;
            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.clickValue) {
                    return;
                }
                if ($scope.saveDataflag == 1) {
                    return;
                };
                setTimeout(function () {
                    $scope.saveDataflag = 0;
                }, 2000);
                $scope.saveDataflag++;
                $scope.clickValue = true;
                var service = "device";
                var reqUrl = "/deliveryReceipt/submit";
                $scope.detailInfo.deliveryReceiptVO.totalWeight = $scope.totalWeight
                var param = $scope.detailInfo;
                $scope.detailInfo.deliveryReceiptVO.deliveryTime
                param.billId = $scope.detailInfo.id;
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/deliveryReceipt/update";
                }
                param.submitType = "1";
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        $scope.clickValue = false;
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.selectedList = [];
                    getDataList();
                    $scope.markInfo.allChecked = false;
                    $scope.orderMarkInfo.allChecked = false;
                    $scope.clickValue = false;
                });
            };

            function getDeliveryStatus() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "WLZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.deliveryStatues = resp.value;
                })
            }

            function getMoreDetailist(curPage) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/moreBillDetail";
                var param = {};
                param.pageSize = $scope.detailPageInfo.pageSize;
                if (!!curPage) {
                    $scope.detailPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.detailPageInfo.curPage;
                param.filters = {
                    billType: $scope.detailInfo.deliveryReceiptVO.billType,
                    deliveryBillId: $scope.detailInfo.deliveryReceiptVO.id
                };
                $scope.billDetailDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailPageInfo.totalRows = resp.value.total;
                    $scope.detailPageInfo.totalPages = resp.value.pages;

                    angular.forEach(resp.value.list, function (item) {
                        item.arrivalTime = item.arrivalTime ? new Date(item.arrivalTime) : '';
                    });
                    $scope.billDetailDataList = resp.value.list;
                });
            }

            $scope.saveDetailData = function (item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/billDetail/edit";
                var param = {
                    billType: 'XGSC',
                    outDetailId: item.outDetailId,
                    backFactory: item.backFactory,
                    remark: item.remark,
                    arrivalTime: item.arrivalTime ? item.arrivalTime.getTime() : undefined

                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                })
            };

            $scope.searchDetail = function (curPage) {
                getMoreDetailist(curPage);
            };
            $scope.initDetail = function (curPage) {
                if (!!$scope.billDetailDataList && $scope.billDetailDataList.length > 0) {
                    return;
                }
                $scope.exportBillDetailParam.param.billType = $scope.detailInfo.deliveryReceiptVO.billType;
                $scope.exportBillDetailParam.param.deliveryBillId = $scope.detailInfo.deliveryReceiptVO.id;
                getMoreDetailist(curPage);
            };

            $scope.makeAbnormal = function (receiptId, receiptNo, orgId) {
                getReceiptDetail(receiptId).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.abnormalObj.headerInfo = {
                        receiptId: receiptId,
                        receiptNo: receiptNo,
                        supplierOrgId: orgId
                    };
                    angular.forEach(data, function (item) {
                        if (item.outQty > item.sendQty) {
                            item.amount = item.outQty - item.sendQty;
                            item.canQty = item.amount;
                            $scope.abnormalObj.detailList.push(item);
                        }
                    });
                    $scope.changeTab(3);
                    if ($scope.inTypeList.length === 0) {
                        getTypeList();
                    }
                });
            };
            $scope.syncPackInfo = function (billNo, billId) {

                var service = "device";
                var reqUrl = "/deliveryReceipt/syncPackInfo";
                var param = {
                    billNo: billNo,
                    billId: billId
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code == 0) {
                        ybWidget.ShowMessage("同步成功", MESG_TYPE.Success);
                        return ;
                    }
                })
            };
            $scope.syncDelivery4NS = function (billId) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/syncDelivery4NS";
                var param = {
                    billId: billId
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return ;
                    }
                    if (resp.code == 0) {
                        ybWidget.ShowMessage("同步成功", MESG_TYPE.Success);
                        return ;
                    }
                })
            };

            function getTypeList() {
                var service = "device";
                var reqUrl = "/billTypeConfig/list";
                var param = {
                    filters: {
                        inOut: 0
                    },
                    pageNum: 0,
                    pageSize: 0
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.inTypeList = resp.value.list;
                })
            }

            function getReceiptDetail(receiptId) {
                var param = {
                    receiptId: receiptId
                };
                return ybHttp.Get('device', '/deliveryReceipt/materialsList', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.saveAbnormalInData = function (isValid) {
                if (angular.isDefined(isValid) && !isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.abnormalObj.detailList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/receiptIn/add";
                var param = angular.copy($scope.abnormalObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            function checkListValid() {
                var isValid = true;
                var errMsgStr = "";
                for (var i = 0, len = $scope.abnormalObj.detailList.length; i < len; i++) {
                    if (!$scope.abnormalObj.detailList[i].qty || parseFloat($scope.abnormalObj.detailList[i].qty) <= 0) {
                        isValid = false;
                        $scope.abnormalObj.detailList[i].qtyErr = true;
                        $scope.abnormalObj.detailList[i].qtyErrMsg = "入库数量不能为空和0";
                        errMsgStr = "零件" + $scope.abnormalObj.detailList[i].materialsNo + "：入库数量不能为空和0";
                        break;
                    }
                    if ($scope.abnormalObj.detailList[i].qty > $scope.abnormalObj.detailList[i].canQty) {
                        isValid = false;
                        $scope.abnormalObj.detailList[i].qtyErr = true;
                        $scope.abnormalObj.detailList[i].qtyErrMsg = "入库数量不能大于可入库数量";
                        errMsgStr = "零件" + $scope.abnormalObj.detailList[i].materialsNo + "：入库数量不能大于可入库数量";
                        break;
                    }
                }
                if (!isValid) {
                    ybWidget.ShowMessage(errMsgStr, MESG_TYPE.Error);
                }
                return isValid;
            }

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    if (!!$scope.abnormalObj.headerInfo.warehouseCode && (data.warehouseCode !== $scope.abnormalObj.headerInfo.warehouseCode)) {
                        $scope.abnormalObj.headerInfo.inArea = "";
                        $scope.abnormalObj.headerInfo.sapInArea = "";
                    }
                    $scope.abnormalObj.headerInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.abnormalObj.headerInfo.warehouseCode = "";
                $scope.abnormalObj.headerInfo.inArea = "";
                $scope.abnormalObj.headerInfo.sapInArea = "";
            };

            $scope.selectArea = function () {
                if (!$scope.abnormalObj.headerInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择领入仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.abnormalObj.headerInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.abnormalObj.headerInfo.inArea = data.areaCode;
                    $scope.abnormalObj.headerInfo.sapInArea = data.sapCode;
                })
            };

            $scope.clearArea = function () {
                $scope.abnormalObj.headerInfo.inArea = "";
                $scope.abnormalObj.headerInfo.sapInArea = "";
            };

            $scope.getInnerOrderList = function (billTypeId) {
                $scope.innerOrderList = [];
                $scope.innerOrder = {
                    item: null
                };
                var service = "device";
                var reqUrl = "/billTypeConfig/item";
                var param = {};
                param.id = billTypeId;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.innerOrderList = resp.value.detailList;
                });
            };

            $scope.checkStock = function (item) {
                item.qtyErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "入库数量不能为空和0";
                    return;
                }
                if (item.qty > 99999.999) {
                    item.qty = 99999.999;
                }
                if (parseFloat(item.qty) > parseFloat(item.canQty)) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "入库数量不能大于可入库数量";
                }
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/remove";
                    var obj = {};
                    obj.id = item.id;
                    ybHttp.Post(service, reqUrl, obj).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            function listWarehouses() {
                var service = "device";
                var reqUrl = "/warehouse/listWarehouses";
                var param = {};
                param.pageSize = 100;
                param.pageNum = 1;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var flag = false;
                    angular.forEach(resp.value.list, function (item) {
                        var warehouse = {};
                        warehouse.code = item.warehouseCode;
                        warehouse.name = item.warehouseCode;
                        $scope.warehouseList.push(warehouse);
                        if ("WJBJ" === item.warehouseCode) {
                            flag = true;
                        }
                    });

                    if (flag) {
                        $scope.orderCondition.warehouseCode = "WJBJ";
                    }
                });
            }

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.abnormalObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.abnormalObj.detailList.length; i < len; i++) {
                    if (!!$scope.abnormalObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.abnormalObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.abnormalObj.detailList[i].isChecked) {
                            $scope.abnormalObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.abnormalObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.sendConfirm = function (billNo) {
                ybWidget.ShowMessage("确定要确认发货吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/shipConfirm";
                    var param = {
                        billNo: billNo
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.outPut = function () {
                if (!$scope.condition.billType) {
                    ybWidget.ShowMessage('请选择单据类型');
                    return false;
                }
                return true;
            };

            $scope.uploadDoc = function (file, index) {
                if (!file) {
                    return;
                }
                if (!/\.(xlsx|xls|doc|docx|pdf|jpeg|png|rar|zip|XLSX|XLS|DOC|DOCX|PDF|JPEG|PNG)$/.test(file.name)) {
                    ybWidget.ShowMessage("请选择 .xlsx .xls .doc .docx .pdf .jpeg .png .rar .zip  格式的文件", MESG_TYPE.Error);
                    return;
                }
                Upload.upload({
                    url: ybConfig.getConfig().baseUrl.Site + "zuul/" + ybConfig.getConfig().serviceName.device + '/deliveryReceipt/uploadAttach',
                    data: {
                        file: file,
                        fileName: file.name,
                        "x-billId": $scope.detailInfo.deliveryReceiptVO.id
                    }
                }).then(function (resp) {
                    var fileObj = {};
                    fileObj.name = resp.config.data.fileName;
                    fileObj.value = resp.data.value;
                    $scope.detailInfo.basicAttachmentList.push(fileObj);
                }, function (resp) {
                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                });
            };

            //删除附件
            $scope.delEnclosure = function (index) {
                $scope.detailInfo.basicAttachmentList.splice(index, 1);
            };

            $scope.downloadAttach = function (id) {
                window.location.href = ybHttp.RequestUrl("device", "/deliveryReceipt/downloadAttach") + '?id=' + id;
            };

            $scope.syncData = function () {
                var service = "device";
                var reqUrl = "/deliveryReceipt/getExpressInfo";
                var param = {
                    deliveryReceiptNo: $scope.detailInfo.deliveryReceiptVO.billNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var reqServerUrl = "/deliveryReceipt/item";
                    var param1 = {
                        billId: $scope.detailInfo.deliveryReceiptVO.id
                    };
                    ybHttp.Get(service, reqServerUrl, param1).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        var dateFrame = "";
                        $scope.detailInfo = resp.value;
                        if (resp.value.logisticsVOList.length > 0) {
                            dateFrame = $filter("YbDate")(resp.value.logisticsVOList[0].createDate);
                            resp.value.logisticsVOList[0].showDate = true;
                        }
                        for (var i = 1, len = resp.value.logisticsVOList.length; i < len; i++) {
                            resp.value.logisticsVOList[i].showDate = true;
                            if ($filter("YbDate")(resp.value.logisticsVOList[i].createDate) === dateFrame) {
                                resp.value.logisticsVOList[i].showDate = false;
                            } else {
                                dateFrame = $filter("YbDate")(resp.value.logisticsVOList[i].createDate);
                            }
                        }
                        $scope.detailInfo = resp.value;
                        EventBus.Publish("setTimeShow", $scope.detailInfo.logisticsVOList);
                        ybWidget.ShowToaster('success', '同步成功');
                    })
                });
            };

            $scope.batchPrint = function () {
                var billIds = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "Handover",
                    cusInterface: '/deliveryReceipt/batchPrintWithUpdate',
                    cusParam: { billIds },
                    isBatchPrint: true
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.batchPrintJckBoxup = function () {
                var billIdList = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIdList.push($scope.dataList[i].id);
                    }
                }
                if (billIdList.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "Encasement4JCK",
                    cusInterface: '/deliveryReceipt/batch4Print',
                    cusParam: { billIdList }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.batchSendConfirm = function () {
                var billNos = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billNos.push({
                            "billNo": $scope.dataList[i].billNo
                        });
                    }
                }
                if (billNos.length === 0) {
                    ybWidget.ShowMessage('请选择需要确认发货的行');
                    return;
                }
                ybWidget.ShowMessage("确定要确认发货吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/batchShipConfirm";
                    ybHttp.Post(service, reqUrl, billNos).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                            return;
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.markInfoForAdd = {};
            $scope.materialsForAdd = [];

            function getList4MaterialInfoWeight() {
                var billTypeRes = $scope.tabFlag.type == 1 ? $scope.detailInfo.deliveryReceiptVO.billType : $scope.orderCondition.billType;
                var params = {
                    billNos: $scope.detailInfo.billList.map(function (item) {
                        return item.deliveryNoteNo;
                    }),
                    billType: billTypeRes
                };
                ybHttp.Get('device', '/deliveryReceipt/list4MaterialInfo', params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var materialInfos = typeof resp.value === 'string' ? [] : resp.value;
                    $scope.totalWeight = materialInfos.reduce(function (total, cur) {
                        if (billTypeRes == 'XGQD') {
                            return total + (cur.weight || 0) * cur.amount
                        }
                        return total + (cur.weight || 0) * cur.qty
                    }, 0)
                    $scope.totalWeight = $filter("decimalPlaces")($scope.totalWeight || 0, 2);
                    if (!!$scope.selectBillFlag) {
                        getFreight()
                        $scope.selectBillFlag = false;
                    }
                    if (!!$scope.delBillFlag) {
                        getFreight();
                        $scope.delBillFlag = false;
                    }
                })
            };

            $scope.selectRowForAdd = function (item, index) {
                if ($scope.markInfoForAdd.cueRow == index) return;
                $scope.markInfoForAdd.cueRow = index;

                var billTypeRes = $scope.tabFlag.type == 1 ? $scope.detailInfo.deliveryReceiptVO.billType : $scope.orderCondition.billType;
                var params = {
                    billNos: [item.deliveryNoteNo],
                    billType: billTypeRes
                };
                ybHttp.Get('device', '/deliveryReceipt/list4MaterialInfo', params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.materialsForAdd = typeof resp.value === 'string' ? [] : resp.value;
                    angular.forEach($scope.materialsForAdd, function (item) {
                        switch (billTypeRes) {
                            case 'XGFT': // 发货通知单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDes;
                                item.qtyC = item.qty;
                                break;
                            case 'XGSC': // 三包出库单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDesc;
                                item.qtyC = item.qty;
                                break;
                            case 'XGQD': // 区域调拨单
                                item.materialNoC = item.materialNo;
                                item.materialDesC = item.materialName;
                                item.qtyC = item.amount;
                                break;
                            case 'XGFC': // 其它出库单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDes;
                                item.qtyC = item.qty;
                                break;
                            case 'XSCK': // 销售赠送出库
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDes;
                                item.qtyC = item.qty;
                                break;
                        }
                    })
                })
            };
            $scope.delBill = function (index, e) {
                e.stopPropagation();
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.detailInfo.billList.splice(index, 1);
                    $scope.delBillFlag = true;
                    getList4MaterialInfoWeight();

                    if (index == $scope.markInfoForAdd.cueRow) {
                        $scope.markInfoForAdd = {};
                        $scope.materialsForAdd = [];
                    } else if (index < $scope.markInfoForAdd.cueRow) {
                        $scope.markInfoForAdd.cueRow -= 1;
                    }
                });
            };

            $scope.autoAddObj = {};
            $scope.sendMethodList = [];

            $scope.needSelCustomer = true; // 客户是否需要手选

            $scope.addDataAuto = function () {
                $scope.autoAddObj = {};
                $scope.billMaterialList = [];
                $scope.saleOrderMaterialList = [];
                $scope.jckBillMaterialList = [];
                $scope.billNoObj = null;
                $scope.saleNoObj = null;
                $scope.jckBillNoObj = null;
                getSendMethods();
                $scope.changeTab(5);
            };

            // 选择仓库
            $scope.selectWarehouse4Auto = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    if (!!$scope.autoAddObj.warehouseCode && (data.warehouseCode !== $scope.autoAddObj.warehouseCode)) {
                        $scope.autoAddObj.areaCode = "";
                    }
                    $scope.autoAddObj.warehouseCode = data.warehouseCode;
                })
            };

            // 选择库区、储位
            $scope.selDepot4Auto = function () {
                if (!$scope.autoAddObj.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择仓库');
                    return;
                }
                var param = {
                    warehouseCode: $scope.autoAddObj.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    $scope.autoAddObj.areaCode = data.areaCode;
                    $scope.autoAddObj.locationCode = data.locationCode;
                })
            };

            // 清空选择的仓库
            $scope.clearWarehouse4Auto = function () {
                $scope.autoAddObj.warehouseCode = "";
                $scope.autoAddObj.areaCode = "";
                $scope.autoAddObj.locationCode = "";
            };

            // 清空选择的库区、储位
            $scope.clearDepot4Auto = function () {
                $scope.autoAddObj.areaCode = "";
                $scope.autoAddObj.locationCode = "";
            };

            // 选择运输方式
            $scope.sendMethodChange = function (item) {
                if (item) {
                    $scope.autoAddObj.shippingMethodId = item.code;
                    $scope.autoAddObj.shippingMethod = item.name;
                } else {
                    $scope.autoAddObj.shippingMethodId = undefined;
                    $scope.autoAddObj.shippingMethod = undefined;
                }
            };

            // 查询运输方式
            function getSendMethods () {
                if ($scope.sendMethodList.length > 0) {
                    return;
                }

                var service = "device";
                var reqUrl = "/sendMethodDictionary/list";
                var param = {pId: 0};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.sendMethodList = resp.value;
                })
            }

            // 选择客户
            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.autoAddObj.dealerOrgName = data.companyName;
                    $scope.autoAddObj.dealerOrgId = data.dealerOrgId;
                });
            };

            // 选择业务员
            $scope.selectCreator = function () {
                var param = {
                    name: "业务员",
                    type: "businessStaff"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.autoAddObj.createName = data.name;
                    $scope.autoAddObj.createId = data.userId;
                });
            };

            $scope.billMaterialList = [];
            $scope.saleOrderMaterialList = [];
            $scope.jckBillMaterialList = [];


            // 选择发运交接单
            $scope.selectBillNo4Auto = function () {
                ybWidget.DataSelector({
                    title: '发运交接单',
                    url: '/deliveryReceipt/list4JckDomestic',
                    otherParams: { isDelivery: 1, outStatus: 2, isLinked: 0 },
                    keyWords: [{label: '发运交接单号', field: 'billNo'}],
                    fields: [
                        {
                            name: '发运交接单号',
                            dataField: 'billNo',
                            width: "100%"
                        }
                    ]
                }).then(function (data) {
                    billNoChange(data);
                })
            };

            // 清空选择的发运交接单
            $scope.clearBillNo4Auto = function () {
                billNoChange(null);
            };

            // 选择发运交接单
            function billNoChange (item) {
                $scope.billNoObj = item;
                if (item) {
                    $scope.autoAddObj.billNo = item.billNo;
                    getHandBillMaterials(item.id).then(function(data) {
                        $scope.billMaterialList = data.materialVOList || [];
                        saleNoChange(data.saleNo);
                    })
                } else {
                    $scope.autoAddObj.billNo = undefined;
                    $scope.billMaterialList = [];
                }

                if ($scope.needSelCustomer) {
                    $scope.autoAddObj.country = item ? item.country : undefined;
                }
            };

            // 选择销售订单
            $scope.selectSaleNo4Auto = function () {
                ybWidget.DataSelector({
                    title: '销售订单',
                    url: '/saleIntention/list',
                    otherParams: { deliveryListFlag: 1 },
                    keyWords: [{label: '销售订单号', field: 'saleNo'}],
                    fields: [
                        {
                            name: '销售订单号',
                            dataField: 'saleNo',
                            width: "100%"
                        }
                    ]
                }).then(function (data) {
                    saleNoChange(data.saleNo);
                })
            };

            // 清空选择的销售订单
            $scope.clearSaleNo4Auto = function () {
                saleNoChange(null);
            };

            // 选择销售订单
            function saleNoChange (val) {
                if(!val){
                    $scope.saleNoObj = null;
                    updateNeedSelCustomerStatus();
                    setDealerOrgVal();
                    $scope.autoAddObj.saleNo = undefined;
                    $scope.saleOrderMaterialList = [];
                    return;
                }
                getOrderDataList(val).then(function(item){
                    $scope.saleNoObj = item;
                    updateNeedSelCustomerStatus();
                    setDealerOrgVal();

                    if (item) {
                        $scope.autoAddObj.saleNo = item.saleNo;
                        getSaleOrderMaterials(item.id).then(function(data) {
                            $scope.saleOrderMaterialList = data || [];
                        })
                    } else {
                        $scope.autoAddObj.saleNo = undefined;
                        $scope.saleOrderMaterialList = [];
                    }
                });

            };

            // 选择进出口运单
            $scope.selectJckBillNo4Auto = function () {
                ybWidget.DataSelector({
                    title: '进出口运单',
                    url: '/deliveryReceipt/list4JckOverseas',
                    otherParams: { deliveryStatus: 0 },
                    keyWords: [{label: '进出口运单号', field: 'billNo'}],
                    fields: [
                        {
                            name: '进出口运单号',
                            dataField: 'billNo',
                            width: "100%"
                        }
                    ]
                }).then(function (data) {
                    jckBillNoChange(data);
                })
            };

            // 清空选择的进出口运单
            $scope.clearJckBillNo4Auto = function () {
                jckBillNoChange(null);
            };

            // 选择进出口运单
            function jckBillNoChange (item) {
                $scope.jckBillNoObj = item;
                updateNeedSelCustomerStatus();
                setDealerOrgVal();
                if (item) {
                    $scope.autoAddObj.jckBillNo = item.billNo;
                    getHandBillMaterials(item.id).then(function(data) {
                        $scope.jckBillMaterialList = data.materialVOList || [];
                    })
                } else {
                    $scope.autoAddObj.jckBillNo = undefined;
                    $scope.jckBillMaterialList = [];
                }
            };

            // 更新客户是否需要手选的状态
            function updateNeedSelCustomerStatus () {
                $scope.needSelCustomer = !$scope.saleNoObj && !$scope.jckBillNoObj;
            }

            // 客户、国家、业务员赋值
            function setDealerOrgVal() {
                if ($scope.jckBillNoObj) {
                    // 客户
                    $scope.autoAddObj.dealerOrgId = $scope.jckBillNoObj.dealerOrgId;
                    $scope.autoAddObj.dealerOrgName = $scope.jckBillNoObj.dealerOrgName;

                    // 国家
                    $scope.autoAddObj.country = $scope.jckBillNoObj.country;

                    // 业务员
                    $scope.autoAddObj.createId = $scope.jckBillNoObj.salesId;
                    $scope.autoAddObj.createName = $scope.jckBillNoObj.salesName;
                } else if ($scope.saleNoObj) {
                    // 客户
                    $scope.autoAddObj.dealerOrgId = $scope.saleNoObj.purchaseOrgId;
                    $scope.autoAddObj.dealerOrgName = $scope.saleNoObj.purchaseOrgName;

                    // 国家
                    $scope.autoAddObj.country = $scope.saleNoObj.country;

                    // 业务员
                    $scope.autoAddObj.createId = $scope.saleNoObj.creatorId;
                    $scope.autoAddObj.createName = $scope.saleNoObj.createName;
                } else {
                    // 客户
                    $scope.autoAddObj.dealerOrgId = undefined;
                    $scope.autoAddObj.dealerOrgName = undefined;

                    // 国家
                    $scope.autoAddObj.country = $scope.billNoObj ? $scope.billNoObj.country : '';

                    // 业务员
                    $scope.autoAddObj.createId = undefined;
                    $scope.autoAddObj.createName = undefined;
                }
            }

            // 查询发运交接单、进出口运单零件详情
            function getHandBillMaterials(id) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/item4Auto";
                var param = {billId: id};
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return sortData(resp.value);
                });
            }

            // 查询销售订单零件详情
            function getSaleOrderMaterials(id) {
                var service = "device";
                var reqUrl = "/saleIntention/item4JckDelivery";
                var param = {id: id};
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return sortData(resp.value);
                });
            }

            // 按零件号排序
            function sortData(data, sortWay) {
                /* if (!data) { data = [] }
                var sortFlagVal
                switch(sortWay) {
                    case 'asc':
                        sortFlagVal = 1;
                        break;
                    case 'desc':
                        sortFlagVal = -1;
                        break;
                    default:
                        sortFlagVal = 1; // 默认升序
                        break;
                }
                data.sort(function(a, b) {
                    if (a.materialsNo > b.materialsNo) return 1 * sortFlagVal
                    if (a.materialsNo == b.materialsNo) return 0
                    if (a.materialsNo < b.materialsNo) return -1 * sortFlagVal
                }) */
                return data;
            }

            // 查询销售订单
            function getOrderDataList(saleNo) {
                var service = "device";
                var reqUrl = "/saleIntention/list";
                var param = {
                    pageNum: 1,
                    pageSize: 10,
                    filters: { deliveryListFlag: 1, saleNo:saleNo}
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return null;
                    }
                    if(resp.value.list.length > 0){
                        return resp.value.list[0];
                    }else{
                        return null;
                    }
                });
            }

            $scope.saveAutoData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }

                var service = "device";
                var reqUrl = "/deliveryReceipt/autoAdd";
                var param = angular.copy($scope.autoAddObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };


            function IsPC() {
                var userAgentInfo = navigator.userAgent.toLowerCase();
                var Agents = ["android", "iphone", "symbianos", "windows phone", "ipad", "ipod"];
                var flag = true;
                for (var v = 0; v < Agents.length; v++) {
                    if (userAgentInfo.indexOf(Agents[v]) > 0) {
                        flag = false;
                        break;
                    }
                }
                return flag;
            }
            $scope.isPC = false;

            (function () {
                $scope.isPC = IsPC();
                getDataList();
                getDeliveryStatus();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                listWarehouses();
            })();
        }]);
})(window, window.angular);
